package com.seeyoui.kensite.bussiness.exam.examResult.service;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.seeyoui.kensite.bussiness.exam.exam.domain.Exam;
import com.seeyoui.kensite.bussiness.exam.exam.service.ExamService;
import com.seeyoui.kensite.bussiness.exam.examResult.util.Marking;
import com.seeyoui.kensite.bussiness.exam.exercise.domain.Exercise;
import com.seeyoui.kensite.common.base.service.BaseService;
import com.seeyoui.kensite.common.util.CacheUtils;
import com.seeyoui.kensite.common.util.DateUtils;

/**
 * 考试评分服务类 MarkingService
 * 
 * @author dico
 * @version 2.0
 * @since 1.0
 * @date 2018-01-08
 */

@Service
public class MarkingService extends BaseService {
	private static Logger logger = LoggerFactory.getLogger(MarkingService.class);

	/** 评分线程锁 */
	private static boolean Locked = false;

	@Autowired
	private ExamService examService;

	/**
	 * 给指定的考试打分
	 * 
	 * @param examId
	 */
	public synchronized void marking(String examId) {
		if (Locked) {
			return;
		}
		Locked = true;

		Exam exam = examService.findOne(examId);
		if (null == exam) {
			logger.error("该试卷不存在：examId=" + examId);
			Locked = false;
			return;
		}

		// 确定评分线程启动时间，在考试结束后的一分钟后启动
		long end = exam.getEndTime().getTime();
		Date now = new Date();
		Date exeTime = null;
		if (now.getTime() < end) {
			exeTime = DateUtils.addMinute(exam.getEndTime(), 1);
		} else {
			exeTime = DateUtils.addMinute(now, 1);
		}

		// 异步评分线程
		Timer timer2Marking = new Timer();
		timer2Marking.schedule(new TimerTask() {
			public void run() {
				Marking marking = new Marking();
				marking.startMarking(examId);
				Locked = false; // 评分完成后解锁
				CacheUtils.remove("QuestionsInExamId_" + examId); // 清理该考试试题缓存
			}
		}, DateUtils.addSecond(new Date(), 20));
		
		// 解锁和清缓存，独立线程处理，避免受到其他意外影响
		Timer timer2Unlock = new Timer();
		timer2Unlock.schedule(new TimerTask() {
			public void run() {
				Locked = false; // 评分完成后解锁
				CacheUtils.remove("QuestionsInExamId_" + examId); // 清理该考试试题缓存
			}
		}, exeTime);
	}
	
	/**
	 * 为指定练习评分
	 * @param exercise
	 */
	public synchronized void markingExercise(Exercise exercise) {
		Marking marking = new Marking();
		marking.startMarkingExercise(exercise);
	}
}